package com.lxy.file.controller;


import com.lxy.file.common.Result;
import com.lxy.file.dto.FileChunkDTO;
import com.lxy.file.dto.MergeDTO;
import com.lxy.file.enums.ExceptionEnum;
import com.lxy.file.service.IUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * @author LiuXiaoYu
 * @date 2021/9/3- 14:58
 */
@RestController
@Slf4j
public class UploadController {

    private final IUploadService uploadService;

    @Autowired
    public UploadController(IUploadService uploadService) {
        this.uploadService = uploadService;
    }

    /**
     * 检查分片是否存在
     * @return 自定义结果
     */
    @PostMapping(value = "/check/file")
    public Result<?> checkChunkExist(FileChunkDTO chunkDTO) {
        Result<?> result;
        try {
            result = uploadService.checkChunkExist(chunkDTO);

            return result;
        } catch (Exception e) {
            log.info("异常",e);
            return Result.error(ExceptionEnum.ERROR,"出现异常");
        }
    }


    /** 异步调用加以控制
     * 上传文件分片
     * @param chunkDTO 分块对象
     * @return 自定义结果
     */
    @PostMapping(value = "/upload/chunk")
    public Result<String> uploadChunk(FileChunkDTO chunkDTO){
        try {
            CompletableFuture<Result<String>> completableFuture = uploadService.uploadChunk(chunkDTO);
            //确保每个分块上传方法都成功执行 加不加无所谓
            completableFuture.get();
            return Result.success("上传此分块成功");
        } catch (Exception e) {
            log.info("上传分块文件controller层时,发生了异常:{},{}",e,e.getMessage());
            return Result.error(ExceptionEnum.UPOLAOD_FILE_FAIL,"上传分块文件接口处发生了异常");
        }

    }

    /**
     * 手动合并该文件的所有文件块
     * @param mergeDTO 合并对象
     * @return 自定义结果
     */
    @PostMapping("/manualMerge")
    public Result<?> manualMerge(MergeDTO mergeDTO){
        try {
             return uploadService.manualMerge(mergeDTO);
        }catch (Exception e){
            return Result.error(ExceptionEnum.ERROR,"手动合成文件时发生错误");
        }
    }

}
